<template>
    <div class="image-compress-container">
      <!-- 上传控件 -->
      <el-upload
        class="upload-demo"
        drag
        name="image"
        :data="{ resolution }"
        action="#"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleFileChange"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽图片到此或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 JPG/PNG/WebP 格式，建议尺寸不超过 5MB
          </div>
        </template>
      </el-upload>
  
      <!-- 分辨率设置 -->
      <div class="resolution-input">
        <el-input
          v-model="resolution"
          placeholder="输入分辨率 (如 1280x720)"
          style="width: 240px"
        >
          <template #prepend>目标分辨率</template>
        </el-input>
        <el-button 
          type="primary" 
          :loading="isLoading"
          @click="startCompress"
        >
          {{ isLoading ? '压缩中...' : '开始压缩' }}
        </el-button>
      </div>
  
      <!-- 预览区域 -->
      <div v-if="uploadedImage" class="preview-area">
        <div class="image-pair">
          <div class="image-item">
            <h4>原图 ({{ originalSize }})</h4>
            <el-image 
              :src="uploadedImage"
              :preview-src-list="[uploadedImage]"
              fit="contain"
              style="max-width: 400px; max-height: 300px;"
            />
          </div>
          <div class="image-item">
            <h4 v-if="compressedUrl">压缩后 ({{ compressedSize }})</h4>
            <el-image 
              v-if="compressedUrl"
              :src="compressedUrl"
              :preview-src-list="[compressedUrl]"
              fit="contain"
              style="max-width: 400px; max-height: 300px;"
            />
            <div v-else class="placeholder">压缩结果将在此显示</div>
          </div>
        </div>
  
        <!-- 结果链接 -->
        <div v-if="compressedUrl" class="result-link">
          <el-link type="primary" :href="compressedUrl" target="_blank">
            {{ compressedUrl }}
          </el-link>
          <el-button 
            type="success" 
            icon="DocumentCopy" 
            @click="copyLink"
          >
            复制链接
          </el-button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  import { ElMessage } from 'element-plus'
  import apis from '@apis' 

  // API 接口 (根据实际接口调整)
  const compressImage = async (data) => {
    return await apis.utils.image.compress(data)
  }
  
  // 响应式数据
  const resolution = ref('1280x720')
  const uploadedImage = ref(null)
  const compressedUrl = ref(null)
  const originalFile = ref(null)
  const isLoading = ref(false)
  const originalSize = ref('')
  const compressedSize = ref('')
  
  // 处理文件选择
  const handleFileChange = (file) => {
    if (!validateImageType(file)) return
    originalFile.value = file.raw
    previewImage(file.raw)
  }
  
  // 图片预览
  const previewImage = (file) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      uploadedImage.value = e.target.result
      originalSize.value = formatFileSize(file.size)
    }
    reader.readAsDataURL(file)
  }
  
  // 开始压缩
  const startCompress = async () => {
    if (!validateResolution()) return
    if (!originalFile.value) {
      ElMessage.warning('请先选择图片')
      return
    }
    try {
      isLoading.value = true
      const formData = new FormData()
      formData.append('image', originalFile.value)
      formData.append('resolution', resolution.value)
      const res = await compressImage(formData)
      compressedUrl.value = res.fileUrl
      compressedSize.value = formatFileSize(res.fileSize)
      ElMessage.success('压缩成功')
    }finally {
      isLoading.value = false
    }
  }
  
  // 校验分辨率格式
  const validateResolution = () => {
    const pattern = /^\d+x\d+$/
    if (!pattern.test(resolution.value)) {
      ElMessage.error('分辨率格式不正确，请使用如 1280x720 的格式')
      return false
    }
    return true
  }
  
  // 校验图片类型
  const validateImageType = (file) => {
    const validTypes = ['image/jpeg', 'image/png', 'image/webp']
    if (!validTypes.includes(file.raw.type)) {
      ElMessage.error('不支持的文件格式')
      return false
    }
    return true
  }
  
  // 文件大小格式化
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i])
  }
  
  // 复制链接
  const copyLink = async () => {
    try {
      await navigator.clipboard.writeText(compressedUrl.value)
      ElMessage.success('链接已复制')
    } catch (error) {
      ElMessage.error('复制失败')
    }
  }
  </script>
  
  <style scoped>
  .image-compress-container {
    max-width: 1000px;
    margin: 20px auto;
    padding: 20px;
  }
  
  .resolution-input {
    margin: 20px 0;
    display: flex;
    gap: 10px;
    align-items: center;
  }
  
  .preview-area {
    margin-top: 30px;
  }
  
  .image-pair {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
  }
  
  .image-item {
    border: 1px dashed #ddd;
    padding: 10px;
    border-radius: 4px;
    text-align: center;
  }
  
  .placeholder {
    height: 300px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
  }
  
  .result-link {
    margin-top: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
  }
  </style>